<template>
  <div class="role-container">
    <!-- 搜索条件卡片 -->
    <a-card class="search-card" :bordered="false">
      <a-form :model="searchForm" class="search-form">
        <div class="search-row">
          <a-form-item label="所属应用" class="search-item">
            <a-select
              v-model:value="searchForm.appId"
              placeholder="请选择应用"
              allowClear
              show-search
              :filter-option="filterApplicationOption"
            >
              <a-select-option
                v-for="app in applicationList"
                :key="app.id"
                :value="app.id"
              >
                {{ app.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="角色名称" class="search-item">
            <a-input
              v-model:value="searchForm.name"
              placeholder="请输入角色名称"
              allowClear
            />
          </a-form-item>
          <a-form-item label="角色编码" class="search-item">
            <a-input
              v-model:value="searchForm.code"
              placeholder="请输入角色编码"
              allowClear
            />
          </a-form-item>
        </div>
        <div class="search-row">
          <a-form-item label="状态" class="search-item">
            <a-select
              v-model:value="searchForm.status"
              placeholder="请选择状态"
              allowClear
            >
              <a-select-option
                v-for="(config, key) in ROLE_STATUS"
                :key="key"
                :value="key"
              >
                {{ config.label }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="" class="search-item search-buttons">
            <a-space>
              <a-button type="primary" @click="handleSearch">
                <template #icon><search-outlined /></template>
                查询
              </a-button>
              <a-button @click="handleReset">
                <template #icon><reload-outlined /></template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </div>
      </a-form>
    </a-card>

    <!-- 角色列表卡片 -->
    <a-card class="role-card" :bordered="false">
      <template #title>
        <div class="card-title">
          <a-button v-permission="'system:role:create'" type="primary" @click="handleAdd">
            <template #icon><plus-outlined /></template>
            添加角色
          </a-button>
        </div>
      </template>
      <a-table
        :columns="columns"
        :data-source="tableData"
        :loading="loading"
        :pagination="false"
        row-key="id"
        size="small"
        bordered
        :scroll="{ x: 1200 }"
      >
        <!-- 状态列 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="ROLE_STATUS[record.status]?.color">
              {{ ROLE_STATUS[record.status]?.label }}
            </a-tag>
          </template>

          <!-- 操作列 -->
          <template v-else-if="column.key === 'action'">
            <a-space>
              <!-- 常用操作直接显示 -->
              <a-button
                v-if="record.status === STATUS_KEYS.ROLE.INIT"
                v-permission="'system:role:update'"
                type="link"
                size="small"
                @click="handleEdit(record)"
              >
                编辑
              </a-button>
              <a-button
                type="link"
                size="small"
                @click="handlePermission(record)"
              >
                授权
              </a-button>

              <!-- 其他操作放在下拉菜单中 -->
              <a-dropdown>
                <template #overlay>
                  <a-menu>
                    <a-menu-item
                      v-if="record.status === STATUS_KEYS.ROLE.ENABLE"
                      v-permission="'system:role:disable'"
                      key="disable"
                      @click="handleDisable(record)"
                    >
                      禁用
                    </a-menu-item>
                    <a-menu-item
                      v-if="record.status !== STATUS_KEYS.ROLE.ENABLE"
                      v-permission="'system:role:enable'"
                      key="enable"
                      @click="handleEnable(record)"
                    >
                      启用
                    </a-menu-item>
                    <a-menu-divider
                      v-if="record.status === STATUS_KEYS.ROLE.INIT"
                    />
                    <a-menu-item
                      v-if="record.status === STATUS_KEYS.ROLE.INIT"
                      v-permission="'system:role:delete'"
                      key="delete"
                      danger
                      @click="handleDelete(record)"
                    >
                      删除
                    </a-menu-item>
                  </a-menu>
                </template>
                <a-button type="link" size="small"
                  >更多 <DownOutlined
                /></a-button>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <a-pagination
          v-model:current="pagination.current"
          v-model:pageSize="pagination.pageSize"
          :total="pagination.total"
          :show-total="(total) => `共 ${total} 条`"
          :page-size-options="['10', '20', '50', '100']"
          show-size-changer
          @change="handlePageChange"
          @showSizeChange="handleSizeChange"
          :locale="{ items_per_page: '条/页', jump_to: '跳至', page: '页' }"
        />
      </div>
    </a-card>

    <!-- 创建/编辑角色对话框 -->
    <create-role
      v-model:visible="createDialogVisible"
      :edit-mode="editMode"
      :role-data="currentRole"
      @success="fetchRoleList"
    />

    <!-- 角色权限管理对话框 -->
    <role-permission
      v-model:visible="permissionDialogVisible"
      :role-data="currentRole"
      :application-code="currentRole.applicationCode"
      @success="handlePermissionSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { message, Modal } from "ant-design-vue";
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  DownOutlined,
} from "@ant-design/icons-vue";
import { getRoleList, enableRole, disableRole, deleteRole } from "@/api/role";
import { getApplicationList } from "@/api/application";
import CreateRole from "./components/CreateRole.vue";
import RolePermission from "./components/RolePermission.vue";
import { ROLE_STATUS, STATUS_KEYS } from "@/constants/constants";

// 表格列定义
const columns = [
  { title: "角色ID", dataIndex: "id", width: 80, align: "center" },
  {
    title: "所属应用",
    dataIndex: "appName",
    width: 120,
    align: "center",
  },
  { title: "角色名称", dataIndex: "name", width: 120, align: "center" },
  { title: "角色编码", dataIndex: "code", width: 120, align: "center" },
  {
    title: "描述",
    dataIndex: "description",
    ellipsis: true,
    align: "center",
    width: 150,
  },
  { title: "状态", dataIndex: "status", width: 80, align: "center" },
  { title: "创建时间", dataIndex: "createTime", width: 150, align: "center" },
  { title: "更新时间", dataIndex: "updateTime", width: 150, align: "center" },
  { title: "操作", key: "action", width: 180, fixed: "right", align: "center" },
];

// 响应式数据
const tableData = ref([]);
const loading = ref(false);
const applicationList = ref([]);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});
const searchForm = reactive({
  appId: null,
  name: null,
  code: null,
  status: null,
});
const createDialogVisible = ref(false);
const editMode = ref(false);
const currentRole = ref({});
const permissionDialogVisible = ref(false);

// 生命周期钩子
onMounted(() => {
  fetchApplicationList();
  fetchRoleList();
});

// 获取应用列表
const fetchApplicationList = async () => {
  try {
    const res = await getApplicationList({
      pageNum: 1,
      pageSize: 1000,
      status: "ENABLE",
    });
    applicationList.value = res.data.items || [];
  } catch (error) {
    console.error("获取应用列表失败:", error);
  }
};

// 应用搜索过滤
const filterApplicationOption = (input, option) => {
  const app = applicationList.value.find((app) => app.id === option.value);
  if (!app) return false;
  const searchText = input.toLowerCase();
  return (
    app.name.toLowerCase().includes(searchText)
  );
};

// 获取角色列表数据
const fetchRoleList = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm,
    };
    const res = await getRoleList(params);
    // 直接使用后端返回的应用信息
    tableData.value = res.data.items || [];
    pagination.total = res.data.total || 0;
  } catch (error) {
    message.error("获取角色列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  fetchRoleList();
};

// 重置搜索条件
const handleReset = () => {
  Object.assign(searchForm, {
    name: "",
    code: "",
    status: undefined,
  });
  pagination.current = 1;
  fetchRoleList();
};

// 分页处理
const handlePageChange = (page) => {
  pagination.current = page;
  fetchRoleList();
};

const handleSizeChange = (current, size) => {
  pagination.current = 1;
  pagination.pageSize = size;
  fetchRoleList();
};

// 添加角色
const handleAdd = () => {
  editMode.value = false;
  currentRole.value = {};
  createDialogVisible.value = true;
};

// 编辑角色
const handleEdit = (record) => {
  editMode.value = true;
  currentRole.value = { ...record };
  createDialogVisible.value = true;
};

// 权限管理
const handlePermission = (record) => {
  currentRole.value = { ...record };
  permissionDialogVisible.value = true;
};

// 权限管理成功回调
const handlePermissionSuccess = () => {
  message.success("权限配置成功");
};

// 启用角色
const handleEnable = (record) => {
  Modal.confirm({
    title: "确认启用",
    content: `确定要启用角色【${record.name}】吗？`,
    okText: "确定",
    cancelText: "取消",
    async onOk() {
      try {
        await enableRole(record.id);
        message.success("启用成功");
        fetchRoleList();
      } catch (error) {
        message.error("启用失败");
      }
    },
  });
};

// 禁用角色
const handleDisable = (record) => {
  Modal.confirm({
    title: "确认禁用",
    content: `确定要禁用角色【${record.name}】吗？`,
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      try {
        await disableRole(record.id);
        message.success("禁用成功");
        fetchRoleList();
      } catch (error) {
        message.error("禁用失败");
      }
    },
  });
};

// 删除角色
const handleDelete = (record) => {
  Modal.confirm({
    title: "确认删除",
    content: `确定要删除角色【${record.name}】吗？`,
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      try {
        await deleteRole(record.id);
        message.success("删除成功");
        // 如果当前页只有一条数据且不是第一页，删除后跳转到上一页
        if (tableData.value.length === 1 && pagination.current > 1) {
          pagination.current--;
        }
        fetchRoleList();
      } catch (error) {
        message.error("删除失败");
      }
    },
  });
};
</script>

<style lang="scss" scoped>
.role-container {
  padding: 16px;

  .search-card {
    margin-bottom: 16px;

    :deep(.ant-card-body) {
      padding: 16px;
    }

    .search-form {
      .search-row {
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
        margin-bottom: 16px;

        .search-item {
          flex: 0 0 calc(33.333% - 11px);
          min-width: 280px;
          margin-bottom: 8px;

          :deep(.ant-form-item-label) {
            width: 80px;
            text-align: right;
          }

          :deep(.ant-form-item-control) {
            flex: 1;
          }
        }
      }

      .search-buttons {
        :deep(.ant-form-item-label) {
          display: none;
        }

        :deep(.ant-space) {
          display: flex;
          justify-content: flex-start;
        }
      }
    }
  }

  .role-card {
    :deep(.ant-card-head) {
      min-height: 48px;
      padding: 0 16px;

      .ant-card-head-title {
        padding: 12px 0;
      }
    }

    :deep(.ant-card-body) {
      padding: 16px;
    }

    .card-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
    }
  }

  .pagination-container {
    margin-top: 16px;
    text-align: right;
  }

  .action-btns {
    display: flex;
    gap: 4px;
    justify-content: center;
  }
}
</style>
